<template>
  <el-scrollbar max-height="200">
    <div class="w-[280px] grid-cols-3 grid gap-2">
      <div
        class="relative flex items-center justify-center rounded-lg aspect-square cursor-pointer shadow border border-[#7d7a7a] border-solid"
      >
        <div class="flex items-center flex-col">
          <el-icon color="white"><Plus /></el-icon>
          <span class="text-white text-[14px]">上传图片</span>
        </div>
        <input
          type="file"
          accept="image/png, image/jpeg, image/jpg"
          @change="updataAvatar"
          class="cursor-pointer w-[100%] h-[100%] opacity-0 absolute top-0 left-0 z-[100]"
        />
      </div>

      <div
        v-for="item in imgList"
        :key="item.id"
        class="relative group flex items-center overflow-hidden justify-center rounded-lg aspect-square cursor-pointer shadow border border-[#545252] border-solid"
        :class="{
          '!border-[#2e2ea3]': props.bgImg == item.bgImgUrlShow,
          '!border-[3px]': props.bgImg == item.bgImgUrlShow,
        }"
      >
        <img :src="item.bgImgUrlShow" alt="" class="w-[100%] h-[100%]" />

        <div
          class="w-full h-full absolute flex justify-around items-center opacity-0 group-hover:opacity-100 top-0 left-0 bg-[rgba(0,0,0,0.7)] text-white text-[13px]"
        >
          <span @click="chooseImg(item.bgImgUrlShow)">选择</span>
          <span @click="deleteImg(item.id)" class="text-[red]">删除</span>
        </div>
      </div>
    </div>
  </el-scrollbar>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import {
  getUserStoryList,
  uploadUserStory,
  deleteUserStory,
} from "@renderer/api/userStory";
let props = defineProps({
  bgImg: {
    type: String,
    default: "",
  },
});
let emit = defineEmits(["update:bgImg"]);
let imgList = ref([]);
onMounted(() => {
  console.log("props.bgImg", props.bgImg);

  // 获取背景图列表
  getBgImgList();
});
const getBgImgList = () => {
  getUserStoryList().then((res: any) => {
    console.log(res);
    if (res.code == 200) {
      imgList.value = res.data;
    }
  });
};
const updataAvatar = (event) => {
  // 获取文件
  let file = event.target.files[0];
  console.log(file);
  if (!file) return;
  let formData = new FormData();
  formData.append("bgImg", file);
  uploadUserStory(formData).then((res: any) => {
    console.log(res);
    if (res.code == 200) {
      getBgImgList();
    }
  });
};
const chooseImg = (img: string) => {
  console.log("img", img);
  emit("update:bgImg", img);
};
const deleteImg = (id) => {
  ElMessageBox.confirm("确定删除该图片吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    deleteUserStory([id]).then((res: any) => {
      if (res.code == 200) {
        getBgImgList();
      }
    });
  });
};
</script>

<style scoped lang="scss"></style>
